<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of upload
 *
 * @author wd
 */
class Do_upload_images_model extends Admin_Model
{

    //文件上传参数
    public $max_size = 30000;       //允许上传的最大值
    public $max_width = 900;   //允许上传的最大宽度 
    public $max_height = 2000;  //允许上传的最大高度
    public $allowed_types = 'gif|jpg|png|jpeg';    //允许上传的文件类型

    function __construct()
    {
        parent::__construct();
//        $this->load->library('FileManager');
    }

    /**
     * 图片上传生成缩略图
     * 
     * @author wd
     * @param $type string 文件路径
     * @return mixed 上传失败返回FALSE/上传成功返回string(文件的URL)
     */

    /**
     * @param int $uid 用户id
     * @return  0上传失败 1上传成功
     */
    public function do_upload_face($type = 'prdouct', $thumb = 0, $thumb_width = 50, $thumb_height = 50)
    {
        if (!$_FILES)
        {
            die();
        }
        $config['upload_path'] = 'upload/' . $type;
        if (!$this->create_dir($config['upload_path']))
        {
            $result = 0;
        } else
        {
            $config['allowed_types'] = $this->allowed_types;        //允许类型
            $config['max_size'] = $this->max_size;     //最大值
            $config['max_width'] = $this->max_width;    //最大宽度
            $config['max_height'] = $this->max_height;    //最大高度
            $config['encrypt_name'] = TRUE;       //设置以加密方式重命名文件
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('faceimg'))
            {  //如果上传失败则给出错误提示
                $result = 0;
            } else
            {
                $data = $this->upload->data();
                if ($data['is_image'])
                {
                    $iconfig = $this->image_map(50, 50);
                    $this->load->library('image_lib');
                    $iconfig['source_image'] = $data['full_path'];
                    $this->image_lib->initialize($iconfig);
                    //如果生成缩略图失败  删除原图
                    if (!$this->image_lib->resize())
                    {
                        unlink($config['upload_path'] . $data['file_name']);
                        $result = 0;
                    } else
                    {
                        $thumb_name = $data['raw_name'] . '_thumb' . $data['file_ext'];  //缩略图名
                        $thumb_path = $config['upload_path'] . $thumb_name;  //缩略图路径
                        //删除原图
                        //unlink($config['upload_path'] . $data['file_name']);
                        //复制头像到固定目录
                        $new_path = 'upload/' . $type;
                        if (!copy($thumb_path, $new_path))
                        {
                            $result = 0;
                        } else
                        {
                            $result = 1;
                        }
                    }
                }
            }
        }
        return $result;
    }

}